package com.highspeed.bdk.gateway.socket.analyze.client;

import com.highspeed.bdk.gateway.socket.analyze.message.gui.command.Command;
import com.highspeed.bdk.gateway.socket.analyze.message.gui.command.CommandManager;

import java.io.*;
import java.net.Socket;
import java.util.*;

/**
 * 客户端，通过类可以向网关发送命令以及接收命令
 */
public class Client {
    private Socket socket;
    private String host;
    private int port;

    public Client() {
    }

    public Client(String host, int port) {
        try {
            socket = new Socket(host, port);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 发送请求
     *
     * @param params 参数
     * @return
     */
    public String senMsg(short cmd, List<Short> params) {
        if (params == null) {
            params = new ArrayList<>(0);
        }
        Command command = Command.getCommand(cmd);
        byte[] request = CommandManager.createRequest(command.getCmd(), params);
        try {
            StringBuilder fileName = new StringBuilder(command.getDesc());
            fileName.append("_操作号").append(command.getCmd()).append("_参数").append(Arrays.toString(params.toArray())).append(".dat");
            File file = new File(fileName.toString());

            //往客户端发送数据
            OutputStream outputStream = socket.getOutputStream();
            outputStream.write(request, 0, request.length);
            outputStream.flush();
//            socket.shutdownOutput();

            //获得输入流，获得返回的数据
            InputStream is = socket.getInputStream();
            BufferedInputStream bis = new BufferedInputStream(is);

            //将返回的信息存储到文件中
            BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(file));
            byte[] bytes = new byte[1024 * 10];
            int len = -1;
            while ((len = bis.read(bytes)) != -1) {
                bos.write(bytes, 0, len);
            }
            bos.close();
            bis.close();
            socket.close();
            return fileName.toString();
        } catch (Throwable e) {
            e.printStackTrace();
        }
        return null;
    }

    public static void main(String[] args) {
        String host = "192.168.0.185";
        int port = 8001;
        Client client = new Client(host, port);
//        Client client = new Client();
        List<Short> params = new ArrayList<>();
        params.add((short) (2));
        params.add((short) (2));
        params.add((short) (9));
        params.add((short) (14));
        client.senMsg((short) 0x84, null);
//        client.senMsg((short) 0x27, params);
//        client.senMsg(Command.OX02, params);
    }


}
